package com.malbbmsomanager;
/************PDADBWebServiceBestBuy - Live Server*****************/
/************PDADBWebServiceBestBuy - Web Server**********************/
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.Patterns;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.malbbmsomanager.R;


public class DM_BBM_Properties extends Activity {
	private static final String TAG = null;
	// private PBDatabaseAdapter dbHelper;
	ProgressDialog mProgressDialog;
	private String DBNAME = "dminvoicemanagerbbm.db";
	private SQLiteDatabase mydb;
	private String SERVER_DETAILS = "serverinfo";
	private String SERVER_DB_LIST = "serverdb";
	String connectionURL;
	int arrayLength = 0;
	EditText etsetnewurl;
	final private static int DIALOG_URLVALIDATE_SUCCESS = 1;
	AlertDialog InvoiceHeaderAlert = null;
	// flag for Internet connection status
	Boolean isInternetPresent = false;
	// Connection detector class
	DM_BBM_ConnectionDetector cd;
	// action bar
	private ActionBar actionBar;

	// Check URL Valid or Invalid
	public void btnSaveUrlProperties(View view) {
		// TODO Auto-generated method stub
		// get Internet status
		isInternetPresent = cd.isConnectingToInternet();

		// check for Internet status
		if (isInternetPresent) {
			// Internet Connection is Present
			// make HTTP requests
			validatingServerUrl();
		} else {
			// Internet connection is not present
			// Ask user to connect to Internet
			showAlertDialog(DM_BBM_Properties.this, "No Internet Connection",
					"You don't have internet connection.", false);
		}

	}

	// Display Network connection Fail Alert
	public void showAlertDialog(Context context, String title, String message,
			Boolean status) {
		AlertDialog alertDialog = new AlertDialog.Builder(context).create();

		// Setting Dialog Title
		alertDialog.setTitle(title);

		// Setting Dialog Message
		alertDialog.setMessage(message);

		// Setting alert dialog icon
		alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);

		// Setting OK Button
		alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
			}
		});

		// Showing Alert Message
		alertDialog.show();
	}

	// Sync and Move back to Settings Page
	public void btnSelectCustomerAccept(View view) {
		InvoiceHeaderAlert.dismiss();
		SynchMainDBList();
	}

	// Exit From Property Screen
	public void btnExitSettings(View view) {
		Intent myIntent = new Intent(view.getContext(),
				DM_BBM_InvoiceMainActivity.class);
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivityForResult(myIntent, 0);
		finish();
		return;
	}

	private void validatingServerUrl() {
		// TODO Auto-generated method stub
		String enteredUrl = etsetnewurl.getText().toString().trim();
		if (Patterns.WEB_URL.matcher(enteredUrl).matches()) {
			Log.v(TAG, "btnSaveUrlSettings");
			Cursor cursurllist = null;
			mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
			try {
				cursurllist = mydb.query(SERVER_DETAILS, null, null, null,
						null, null, null);
			} catch (Exception e) {
			}

			if (cursurllist == null || cursurllist.getCount() < 1) {
				try {
					ContentValues savenewurl = new ContentValues();
					// http://220.247.242.201:1025
					savenewurl.put("serverurl", etsetnewurl.getText()
							.toString());
					savenewurl.put("portval", "8080");

					mydb.insert(SERVER_DETAILS, null, savenewurl);
				} catch (Exception e) {
					// Toast.makeText(this, e.toString(),
					// Toast.LENGTH_LONG).show();
				}
				getLatestServerUrl();
				Log.v(TAG, "getLatestServerUrl 1");
			} else {
				ContentValues updatenewurl = new ContentValues();
				updatenewurl.put("serverurl", etsetnewurl.getText().toString());
				updatenewurl.put("portval", "8080");
				mydb.update(SERVER_DETAILS, updatenewurl, "server_id ='1'",
						null);

			}

			try {
				showDialog(DIALOG_URLVALIDATE_SUCCESS);
			} catch (Exception ex) {
				ex.printStackTrace();
			}
			// Toast.makeText(this, "URL is valid!", Toast.LENGTH_LONG).show();
		} else {
			etsetnewurl.setText("");
			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_BBM_Properties.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("INVALID URL");
			// Setting Dialog Message
			alertDialog
					.setMessage("Invalid URL Entered.Please Enter Valid URL.");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			;
			alertDialog.setCanceledOnTouchOutside(false);
			alertDialog.show();
			return;
			// Toast.makeText(this, "URL is invalid!",
			// Toast.LENGTH_LONG).show();
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_bbm_properties);
		
		actionBar = getActionBar();
		// Hide the action bar title
		actionBar.setDisplayShowTitleEnabled(true);
		actionBar.setDisplayHomeAsUpEnabled(false);
		// Enabling Spinner dropdown navigation
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
		// creating connection detector class instance
		cd = new DM_BBM_ConnectionDetector(getApplicationContext());
		etsetnewurl = (EditText) findViewById(R.id.etsetserverurl);
	}

	// Retrieve Current URL
	private void getLatestServerUrl() {
		// TODO Auto-generated method stub
		Cursor getserverurl = null;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		try {
			getserverurl = mydb.query(SERVER_DETAILS, null, null, null, null,
					null, null);
		} catch (Exception e) {
		}
		if (getserverurl != null) {
			if (getserverurl.getCount() > 0) {
				while (getserverurl.moveToNext()) {
					connectionURL = getserverurl.getString(1);
					Log.v(TAG, "connectionURL:" + connectionURL);
				}
			}
		}

		mydb.close();
	}

	private void SynchMainDBList() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor cursdblist = null;
		try {
			cursdblist = mydb.query(SERVER_DB_LIST, null, null, null, null,
					null, null);
		} catch (Exception e) {
		}

		if (cursdblist == null) {
			Log.v(TAG, "Call Web Service 1");
			new DownloadAdministrativeDBList().execute();
		} else if (cursdblist.getCount() < 1) {
			Log.v(TAG, "Call Web Service 2");
			new DownloadAdministrativeDBList().execute();
		} else {

			Intent intentDirectLog = new Intent(getBaseContext(),
					DM_BBM_Settings.class);
			intentDirectLog.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			intentDirectLog.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intentDirectLog.putExtra("TAGID", "6");
			startActivity(intentDirectLog);
			mydb.close();
			finish();
			return;
		}
	}

	private class DownloadAdministrativeDBList extends
			AsyncTask<Void, Void, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressdialog
			mProgressDialog = new ProgressDialog(DM_BBM_Properties.this);
			mProgressDialog.setMax(100);
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			mProgressDialog.setCancelable(false);
			// Set progressdialog title
			mProgressDialog.setTitle("Downloading Details");
			// Set progressdialog message
			mProgressDialog.setMessage("Loading Details...");
			mProgressDialog.setIndeterminate(false);
			// Show progressdialog
			mProgressDialog.show();
		}

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			// *****************Download Available Data Bases**************
			try {
				// Replace it with your own WCF service path
				/*String MainUrl = connectionURL
						+ "/PDADBWebService/PDADBWebServiceRest.svc/GetdatabaseNames/mobile123";*/
				/*String MainUrl = connectionURL
				+ "/PDADBWebService/PDADBWebServiceRest.svc/GetdatabaseNames/mobile123";*/
				
				
				//+++++++++++++PDADBWebServiceBBM++++++++++++++++
				//+++++++++++++PDADBWebServiceBestBuy++++++++++++++++
				/*String MainUrl = connectionURL
						+ "/PDADBWebServiceBestBuy/PDADBWebServiceRest.svc/GetdatabaseNames/mobile123";*/
				
				String MainUrl = connectionURL
						+ "/PDADBWebServiceBBM/PDADBWebServiceRest.svc/GetdatabaseNames/mobile123";
				Log.v(TAG, "MainUrl :" + MainUrl);
				

				URL json = new URL(MainUrl);
				URLConnection jc = json.openConnection();
				BufferedReader readerfdblist = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfdblist.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArray = jsonResponse
						.getJSONArray("GetdatabaseNamesResult");
				for (int i = 0; i < jsonArray.length(); i++) {
					progressHandler
							.sendMessage(progressHandler.obtainMessage());
					JSONObject jObject = (JSONObject) jsonArray.get(i);
					String sdbname = jObject.getString("Name");
					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowdblist = new ContentValues();
					Cursor sdblistrows = null;
					try {
						sdblistrows = mydb.query(SERVER_DB_LIST, null,
								"sdbname ='" + sdbname + "'", null, null, null,
								null);
					} catch (Exception e) {
					}
					if (sdblistrows == null) {
						arrayLength = arrayLength + 1;
						Log.v(TAG, "DB 1:" + sdbname.trim());
						newrowdblist.put("sdbname", sdbname.trim());
						mydb.insert(SERVER_DB_LIST, null, newrowdblist);
						sdblistrows.close();
						mydb.close();
					} else if (sdblistrows.getCount() < 1) {
						arrayLength = arrayLength + 1;
						Log.v(TAG, "DB 2:" + sdbname.trim());
						newrowdblist.put("sdbname", sdbname.trim());
						mydb.insert(SERVER_DB_LIST, null, newrowdblist);
						sdblistrows.close();
						mydb.close();
					}
					mydb.close();
				}

				readerfdblist.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}

			return null;
		}

		// handler for the background updating
		Handler progressHandler = new Handler() {
			public void handleMessage(Message msg) {
				mProgressDialog.incrementProgressBy(arrayLength);
			}
		};

		@Override
		protected void onPostExecute(Void args) {

			mProgressDialog.dismiss();
			Intent intentLogin = new Intent(getBaseContext(), DM_BBM_Settings.class);
			intentLogin.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			intentLogin.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intentLogin.putExtra("TAGID", "6");
			startActivity(intentLogin);
			finish();
			return;

		}
	}

	// Handling Dialog Box Functions
	@Override
	protected Dialog onCreateDialog(int id) {

		switch (id) {
		case DIALOG_URLVALIDATE_SUCCESS:
			LayoutInflater inflater = LayoutInflater.from(this);
			View dialogview = inflater.inflate(
					R.layout.dm_bbm_dialog_select_customer, null);

			AlertDialog.Builder dialogbuilder = new AlertDialog.Builder(this);
			dialogbuilder.setTitle("Server URL Configuration Success...");
			dialogbuilder.setView(dialogview);
			InvoiceHeaderAlert = dialogbuilder.create();
			InvoiceHeaderAlert.setCanceledOnTouchOutside(false);
			break;
		}
		return InvoiceHeaderAlert;
	}

	@Override
	public void onBackPressed() {
		// Do Here what ever you want do on back press;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_search:
			// search action
			return true;
		case R.id.action_location_found:
			// location found
			LocationFound();
			return true;
		case R.id.action_refresh:
			// refresh
			return true;
		case R.id.action_help:
			// help action
			return true;
		case R.id.action_check_updates:
			// check for updates action
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private void LocationFound() {
		// TODO Auto-generated method stub
		Intent myIntent = new Intent(getBaseContext(),
				DM_BBM_InvoiceMainActivity.class);
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivityForResult(myIntent, 0);
		finish();
		return;
	}
	
	public boolean onNavigationItemSelected(int itemPosition, long itemId) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main_actions, menu);
		return true;
	}

}
